package com.wenxi.controller;

import com.wenxi.Entity.XmlMessageEntity;
import com.wenxi.utils.SecurityUtil;
import com.wenxi.utils.WeixinUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.Date;

@Controller
public class ValidateController {

    @RequestMapping(value = "/weixinValidate",method = RequestMethod.GET)
    @ResponseBody
    public String weixinValidate(String signature, String timestamp, String nonce, String echostr ){

        // 1）将token、timestamp、nonce三个参数进行字典序排序
        String[] arrs = {WeixinUtil.TOKEN,timestamp,nonce}; //WeixinUtil.TOKEN： 抽取出来的TOKEN，为了重用
        Arrays.sort(arrs);
        // 2）将三个参数字符串拼接成一个字符串进行sha1加密
        String str = arrs[0] + arrs[1] + arrs[2];
        // 3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
        if (signature.equals(SecurityUtil.SHA1(str))){
            //确认此次GET请求来自微信服务器,返回echostr参数内容，则接入生效，成为开发者成功，否则接入失败
            return echostr;
        }else
            return null;
    }

    /**
     * 自动回复信息
     */
    @RequestMapping(value = "weixinValidate",method = RequestMethod.POST)
    @ResponseBody
    public XmlMessageEntity weixinValidate(@RequestBody XmlMessageEntity entity){
        System.out.println(entity);
        XmlMessageEntity returnMessageEntity = new XmlMessageEntity();
        returnMessageEntity.setFromUserName(entity.getToUserName());
        returnMessageEntity.setToUserName(entity.getFromUserName());
        returnMessageEntity.setCreateTime(new Date().getTime());
        returnMessageEntity.setMsgType("text");

        String content = "";
        //判断消息类型为event
        if ("event".equals(entity.getMsgType())) {
            //关注
            if ("subscribe".equals(entity.getEvent())) {
                content = "欢迎大家关注！";
                //TODO 插入关注记录到数据库
            }else if ("unsubscribe".equals(entity.getEvent())) {
                //取消关注

                //TODO 更改关注状态为取消关注
            }
        }else {  //普通消息
            //根据关键字回复
            if ("暑假放多久".equals(entity.getContent())){
                content = "暑假为2个月！";
            }else{
                //不是关键字统一回复
                content = "暂时没有匹配的回复！";
            }
            //TODO 这里可以保存用户的消息用于统计问题
        }
        returnMessageEntity.setContent(content);
        return returnMessageEntity;
    }
}
